/**
 * Copyright (c) 2011-2023, James Zhan 詹波 (jfinal@126.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jse.tpl;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
 * Template
 * 
 * 用法：
 * Template template = Engine.use().getTemplate(...);
 * template.render(data, writer);
 * template.renderToString(data);
 */
public class Template {
	
	private Env env;
	private Stat ast;
	
	public Template(Env env, Stat ast) {
		if (env == null || ast == null) {
			throw new IllegalArgumentException("env and ast can not be null");
		}
		this.env = env;
		this.ast = ast;
	}
	
	/**
	 * 执行解析函数 如sql模块
	 * @param scope
	 * @param writer
	 */
	public void exec(Scope scope,Writer writer) {
		ast.exec(env,null,null);
	}
	
	/**
	 * 渲染到 OutputStream 中去
	 */
	public void render(Object obj, OutputStream out) {
		try (ByteWriter write = env.engineConfig.writerBuffer.getByteWriter(out)) {
			if(obj==null) {
				ast.exec(env, new Scope(new HashMap<>(), env.engineConfig.sharedObjectMap), write);
			}else if(obj instanceof Map<?,?> data) {
				ast.exec(env, new Scope(data, env.engineConfig.sharedObjectMap), write);
			}else {
				ast.exec(env, new Scope(Map.of("p",obj), env.engineConfig.sharedObjectMap),write);
			}
		}
	}
	/**
	 * 渲染到 Writer 中去
	 */
	public void render(Object obj, Writer writer) {
		try (CharWriter write = env.engineConfig.writerBuffer.getCharWriter(writer)) {
			if(obj==null) {
				ast.exec(env, new Scope(new HashMap<>(), env.engineConfig.sharedObjectMap), write);
			}else if(obj instanceof Map<?,?> data) {
				ast.exec(env, new Scope(data, env.engineConfig.sharedObjectMap), write);
			}else {
				ast.exec(env, new Scope(Map.of("p",obj), env.engineConfig.sharedObjectMap), write);
			}
			
		}
	}
	/**
	 * 渲染到 String 中去
	 * @throws IOException 
	 */
	public String renderToString(Object obj){
		try (Writer fsw = env.engineConfig.writerBuffer.getStringWriter()) {
		
//		try (FastStringWriter fsw = env.engineConfig.writerBuffer.getFastStringWriter()) {
			if(obj==null) {
				render(new HashMap<>(), fsw);
			}else if(obj instanceof Map<?,?> data) {
				render(data, fsw);
			}else {
				render(Map.of("p",obj), fsw);
			}
			return fsw.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public boolean isModified() {
		return env.isSourceListModified();
	}
}





